﻿using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FanaticRock.Core.DI;
using FanaticRock.Core.Extensions;
using FanaticRock.Core.Interfaces;
using FanaticRock.Extensions;
using FanaticRock.Helpers;
using FanaticRock.MediaSource.BilibiliAPI.API.Fav.Resource;
using FanaticRock.MediaSource.BilibiliAPI.Interfaces;
using FanaticRock.MediaSource.BilibiliAPI.RequestVo.Fav.Resource;
using FanaticRock.MediaSource.BilibiliAPI.ResponseDto.Fav.Resource;
using Microsoft.VisualBasic;

namespace FanaticRock.ViewModels
{
    ///<summary>延迟获取收藏夹里的曲子。</summary>
    [InjectMe(LifeTimeType = InjectMeAttribute.LifeTimeEnum.Trans)]
    [INotifyPropertyChanged]
    public partial class LazyQuerySongsViewModel : ILogger
    {
        #region services

        private IBilibiliCookieService _bilibiliCookieService;

        #endregion

        #region fields

        ///<summary>B站收藏夹 id</summary>
        private long _folderId;

        ///<summary>临时取得的收藏夹的全部信息。</summary>
        private IdsResponseDto _albumIds;

        private int _pageSize = 40;
        private int _pageIndex = 0;
        private bool _isRequesting = false;

        private bool _isDownloadAll = false;

        #endregion

        #region props

        // 收藏夹中的全部视频。
        [ObservableProperty]
        private ObservableCollection<BvidSongViewModel> _albumSongs = new ObservableCollection<BvidSongViewModel>();

        [ObservableProperty]
        private bool _hasMore = true;



        #endregion

        #region ctors

        public LazyQuerySongsViewModel(IBilibiliCookieService bilibiliCookieService)
        {
            _bilibiliCookieService = bilibiliCookieService;
        }

        public async Task Init(long id)
        {
            var idsDto = await Ids.Invoke(new IdsRequestVo(id));
            _albumIds = idsDto;
            _folderId = id;
            RequestNext();
        }

        #endregion

        #region methods

        ///<summary>获得收藏夹里面的歌词。</summary>
        public async Task<IEnumerable<BvidSongViewModel>> GetAlbumSongs(long id, IdsResponseDto idsResponseDto, int pageSize, int pageIndex)
        {

            var mid = await _bilibiliCookieService.GetMId();
            var folderId = id;

            var resourceList = idsResponseDto.List
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize)
                .Select(i => new ResourceInfo(i.id));

            var infosDto = await Infos.Invoke(new InfosRequestVo(resourceList, mid, folderId.ToString()));

            return infosDto.List.Select(i =>
            {
                var newSongViewModel = new BvidSongViewModel(i);
                return newSongViewModel;
            });
        }

        ///<summary>调用下一次请求。</summary>
        public async Task RequestNext()
        {
            if (_isRequesting) { this.Info($"LazyQuerySongsViewModel.RequestNext: 该查询正在请求中，无法进行重复的请求"); return; }
            _isRequesting = true;
            if (HasMore == false) { this.Info($"LazyQuerySongsViewModel.RequestNext: 已经到底了"); return; };
            try
            {
                var id = _folderId;
                var idResponseDto = _albumIds;
                var pageSize = _pageSize;
                var pageIndex = _pageIndex + 1;
                var albumSongs = await GetAlbumSongs(id, idResponseDto, pageSize, pageIndex);
                _pageIndex = pageIndex; // 避免崩掉的时候，下一次切换页面出现问题。

                BindingOperations.EnableCollectionSynchronization(albumSongs, ObservableCollectionHelper._lockObj);

                foreach (var song in albumSongs)
                {
                    _albumSongs.Add(song);
                }
                BindingOperations.DisableCollectionSynchronization(albumSongs);

            }
            catch (Exception ex)
            {
                this.Info($"LazyQuerySongsViewModel.RequestNext: {ex}");
            }
            finally
            {
                _albumSongs.UpdateIndex();
                HasMore = CanRequestNext();
                _isRequesting = false;

                NoticeHelper.Notice("载入完成！");
            }
        }

        ///<summary>是否还有更多。</summary>
        public bool CanRequestNext()
        {
            var pageMax = _pageSize * _pageIndex;

            var total = 0;
            if (_albumIds != null && _albumIds.List != null) total = _albumIds.List.Length;

            // 页面承载的总数总是会小一些。
            return pageMax < total;
        }

        [RelayCommand]
        public async void DownloadAll()
        {
            if (_isDownloadAll == true)
            {
                NoticeHelper.Notice("正在下载，请勿重复调用");
                return;
            }

            NoticeHelper.Notice("开始下载");

            _isDownloadAll = true;
            while (_hasMore)  // 遍历得到全部内容。
            {
                await RequestNext();
            }

            var clonedColl = new List<BvidSongViewModel>(_albumSongs);
            foreach (var song in clonedColl)
            {
                await song.DownloadCore();
                await Task.Delay(500);
            }

            NoticeHelper.Notice("任务完成",$"全部共 {clonedColl.Count} 首歌曲下载完成。");

            _isDownloadAll = false;
        }

        public void Dispose()
        {
            _albumSongs.Clear();
        }

        #endregion
    }
}
